package starlink

import (
	"errors"
	"github.com/Unixeno/TheMoon/common/util"
	"github.com/Unixeno/TheMoon/logging"
	"github.com/Unixeno/TheMoon/moon/config"
	"github.com/Unixeno/TheMoon/moon/starlink/clients/tcpclient"
	"time"
)

var logger = logging.GetLogger("starlink")

func GetClient() (Client, error) {
	cfg := config.SysConfig
	var client Client

	if id, ok := util.ParsePlanetID(config.SysConfig.StartLink.PlanetID); !ok {
		return nil, errors.New("invalid planet ID")
	} else {
		logger.WithField("PlanetID", id).Info()
	}

	switch cfg.StartLink.ClientType {
	case "tcp":
		clientConfig := tcpclient.ClientConfig{
			Addr:             cfg.StartLink.Server,
			NodeID:           cfg.NodeID,
			HandshakeTimeout: time.Duration(cfg.StartLink.HandshakeTimeout) * time.Second,
			ReadDeadline:     time.Duration(cfg.StartLink.ReadDeadline) * time.Second,
			WriteDeadline:    time.Duration(cfg.StartLink.WriteDeadline) * time.Second,
			CAFile:           cfg.StartLink.CAFile,
			CertFile:         cfg.StartLink.CertFile,
			PrivateKeyFile:   cfg.StartLink.PrivateKeyFile,
		}
		client = tcpclient.CreateClient(&clientConfig, config.SysConfig.StartLink.PlanetID)
		break
	default:
		return nil, errors.New("unsupported client type")
	}
	return client, nil
}
